import {
  Controller,
  Post,
  Body,
  Req,
  HttpCode,
  UnauthorizedException,
  UseInterceptors,
  UploadedFile,
} from '@nestjs/common';
import { Request } from 'express';
import { UserService } from './user.service';
import { AuthService } from '../auth/auth.service';
import { GetWechatPhoneDto } from '@/common/platform/wechat/dto/get-phone.dto';
import { FileInterceptor } from '@nestjs/platform-express';

@Controller('user')
export class UserController {
  constructor(
    private readonly userService: UserService,
    private readonly authService: AuthService,
  ) {}

  @Post('/login')
  @HttpCode(200)
  async login(
    @Body() { code }: { code: string },
    @Req() req: Request,
  ): Promise<{ token: string }> {
    const user = await this.userService.createUser(code, req);
    return user;
  }

  @Post('/getWechatPhone')
  @HttpCode(200)
  async getWechatPhone(
    @Body() info: GetWechatPhoneDto,
    @Req() req: Request,
  ): Promise<any> {
    // 直接从headers中获取token（图片显示token是独立字段，非Authorization头）
    const authHeader = req.headers['token'] as string; // 明确类型为string

    if (!authHeader) {
      throw new UnauthorizedException('未提供授权token');
    }
    const token = authHeader.replace(/^Berear\s+/i, ''); // 不区分大小写替换

    return this.userService.getUserPhone(info, token);
  }

  @Post('/getWechatNickName')
  @HttpCode(200)
  async getWechatNickName(
    @Body() info: GetWechatPhoneDto,
    @Req() req: Request,
  ): Promise<any> {
    // 直接从headers中获取token（图片显示token是独立字段，非Authorization头）
    const authHeader = req.headers['token'] as string; // 明确类型为string

    if (!authHeader) {
      throw new UnauthorizedException('未提供授权token');
    }
    const token = authHeader.replace(/^Berear\s+/i, ''); // 不区分大小写替换

    return this.userService.getUserNickName(info, token);
  }

  @Post('/images/upload')
  @UseInterceptors(FileInterceptor('file'))
  async uploadAvatar(
    @UploadedFile() file: Express.Multer.File,
    @Body('openId') openId: string, // 直接解构出userId
  ) {
    const url = await this.userService.updateUserAvatar(file, openId);
    return {
      url: url,
    };
  }
}
